1669. 合并两个链表
为保证权益,题目请参考 1669. 合并两个链表(From LeetCode).
解决方案1
CPP
C++
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
ListNode* removeStartNode = nullptr;
ListNode* removeEndNode = nullptr;
ListNode* t = list1;
for (int i = 1;; i++) {
if (a == i) {
removeStartNode = t;
}
if (b == i) {
removeEndNode = t->next->next;
break;
}
t = t->next;
}
// delete
t = removeStartNode->next;
while (t->next != removeEndNode) {
ListNode* t2 = t->next;
delete t;
t = t2;
}
// add
removeStartNode->next = list2;
t = list2;
while (t->next != nullptr) {
t = t->next;
}
t->next = removeEndNode;
return list1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47